package com.taotao.portal.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.CookieUtils;
import com.taotao.common.utils.HttpClientUtil;
import com.taotao.pojo.TbUser;

@Service
public class UserServiceImpl implements UserService {
	@Value("${SSO_BASE_URL}")
	private String SSO_BASE_URL;
	@Value("${SSO_USER_TOKEN_URL}")
	private String SSO_USER_TOKEN_URL;

	@Override
	public TbUser getUserByToken(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			// Cookie中获取token
			String token = CookieUtils.getCookieValue(request, "TT_TOKEN");
			// 判断token是否存在
			if (StringUtils.isBlank(token)) {
				return null;
			}
			// 调用taotao-sso系统查询user信息的服务
			String json = HttpClientUtil.doGet(SSO_BASE_URL
					+ SSO_USER_TOKEN_URL + token);
			// 判断用户信息是否过期
			if (TaotaoResult.format(json).getStatus() != 200) {
				return null;
			}
			;
			// 得到user信息
			TbUser user = (TbUser) TaotaoResult
					.formatToPojo(json, TbUser.class).getData();
			return user;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
